<template>
  <el-table
    @row-contextmenu="rightClick"
    border
    id="iTable"
    v-loading.iTable="options.loading"
    stripe
    :data="visibleLists"
    :stripe="false"
    ref="mutipleTable"
    empty-text=" "
    :header-cell-style="{ background: '#F6F8FB' }"
    :row-class-name="TableRowClassName"
    v-scrollbar="'.el-table__body-wrapper'"
    :height="maxHeight"
  >
    <!--数据列-->
    <template v-for="(column, index) in columns">
        <template v-if="column.prop.indexOf('{')>-1">
          <template
            v-for="n in 10">
            <el-table-column
              :show-overflow-tooltip="column.showOverflow"
              :prop="column.prop.replace(/{id}/g,n)"
              :key="column.prop.replace(/{id}/g,n)"
              :label="column.name+n"
              :align="column.align"
              :width="hasResize ? column.showWidth : column.width"
              :sortable="column.sortable"
              v-if="list[0]&&list[0][column.prop.replace(/{id}/g,n)]&&column.show">
            </el-table-column>
          </template>
        </template>
        <template v-else>
          <el-table-column
            :show-overflow-tooltip="column.showOverflow"
            :prop="column.prop"
            :key="column.name"
            :label="column.name"
            :align="column.align"
            :width="hasResize ? column.showWidth : column.width"
            :sortable="column.sortable"
            v-if="column.show"
          >
            <template slot="header" slot-scope="scope">
              <template
                v-if="
                  column.prop == options.expandColumn || column.prop == 'folderName'
                "
              >
                <el-checkbox
                  :indeterminate="rootList.isIndeterminate"
                  v-model="rootList.checked"
                  @change="HandleRootCheckedChange(rootList)"
                >
                </el-checkbox>
                <span
                  class="expand-icon"
                  v-if="rootList.collapsed"
                  style="background-color: #fff; border-radius: 50%"
                  @click="HandleExpandAll()"
                >
                </span>
                <span
                  class="expand-icon expanded"
                  v-else
                  style="background-color: #fff; border-radius: 50%"
                  @click="HandleExpandAll()"
                >
                </span>
              </template>
              {{ column.name }}
            </template>

            <template slot-scope="scope">
              <template
                v-if="
                  column.fullEdit != null &&
                  column.fullEdit != undefined &&
                  dynamicEval(scope.row,String(column.fullEdit)) &&
                  editall
                "
              >
                <template v-if="addFormData[column.prop] != undefined">
                  <dynamic-form-item
                    :addform="[addFormData[column.prop]]"
                    :form="scope.row"
                  >
                  </dynamic-form-item>
                </template>
                <template v-else>
                  <el-input v-model="scope.row[column.prop]"></el-input>
                </template>
              </template>
              <template v-else>
                <template v-if="!column.render">
                  <template
                    v-if="
                      column.prop == options.expandColumn ||
                      column.prop == 'folderName'
                    "
                  >
                    <el-checkbox
                      :indeterminate="scope.row.isIndeterminate"
                      v-model="scope.row.checked"
                      @change="HandleCheckedChange(scope.row)"
                      :style="{ marginLeft: scope.row.parents.length * 16 + 'px' }"
                      :disabled="uncheck.includes(scope.row.id)"
                    >
                    </el-checkbox>
                    <span
                      class="expand-icon"
                      v-if="scope.row.collapsed"
                      @click="HandleExpand(scope.row.id)"
                    >
                    </span>
                    <span
                      class="expand-icon expand"
                      v-else
                      @click="HandleExpand(scope.row.id)"
                    ></span>
                    <i
                      class="remarkpaste el-icon-s-flag"
                      v-if="scope.row.paste"
                    ></i>
                  </template>
                  <template v-if="column.propType === 'list'">
                    <template
                      v-if="
                        scope.row[column.prop] && scope.row[column.prop].length >= 1
                      "
                    >
                      <el-dropdown placement="bottom">
                        <span class="el-dropdown-link">
                          {{ scope.row[column.prop].length }}
                          <i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu
                          slot="dropdown"
                          v-scrollbar
                          style="max-height: 300px; overflow: hidden; z-index: 1000"
                        >
                          <template v-for="file in scope.row[column.prop]">
                            <el-dropdown-item
                              class="item"
                              :key="file.id"
                              :command="file"
                            >
                              <a
                                style="text-decoration: underline; color: #409eff"
                                @click="
                                  preview(
                                    file.path,
                                    scope.row['stateid'],
                                    scope.row['id'],
                                    file.id
                                  )
                                "
                              >
                                {{ file.fileName }}
                              </a>
                            </el-dropdown-item>
                          </template>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </template>
                    <template v-else> 0 </template>
                    <!-- <div
                        v-for="(item, index) in scope.row[column.prop]"
                        :key="index"
                      >
                        <a
                          style="text-decoration: underline; color: #409eff"
                          @click="
                            preview(
                              item.path,
                              scope.row['stateid'],
                              scope.row['docId']
                            )
                          "
                        >
                          {{ item.fileName }}
                        </a>
                      </div> -->
                  </template>
                  <template v-else-if="column.propType === 'date'">
                    <span>{{ scope.row[column.prop].split(" ")[0] }}</span>
                  </template>
                  <template v-else-if="column.propType === 'link'">
                    <span class="link-type" @click="jumpTo(scope.row, column)">{{
                      scope.row[column.prop]
                    }}</span>
                  </template>
                  <template v-else-if="column.propType === 'button'">
                    <span
                      @click="
                        clickEvent(
                          {
                            url: column.url,
                            pageParams: column.pageParams,
                            type: 1,
                            name: column.name,
                          },
                          scope.row
                        )
                      "
                    >
                      {{ scope.row[column.prop] }}
                      <i class="el-icon-plus"></i>
                    </span>
                  </template>
                  <template v-else-if="column.propType === 'progress'">
                    <el-progress
                      :text-inside="true"
                      :stroke-width="26"
                      :percentage="scope.row[column.prop]"
                    >
                    </el-progress>
                  </template>
                  <template v-else-if="column.propType === 'rate'">
                    <el-rate
                      disabled
                      text-color="#ff9900"
                      v-model="scope.row[column.prop]"
                      show-score
                    >
                    </el-rate>
                  </template>
                  <template v-else-if="column.propType === 'image'">
                    <img
                      :src="scope.row[column.prop]"
                      alt="问题图片"
                      style="width: 20px; height: 20px"
                      @click="imgPreview(scope.row[column.prop])"
                    />
                  </template>
                  <template v-else-if="column.propType === 'icon'">
                    <img
                      v-if="dynamicEval(scope.row, column.pageParams)"
                      :src="dynamicEval(scope.row, column.pageParams)"
                      alt="图标"
                    />
                  </template>
                  <template v-else>
                    <template v-if="Array.isArray(scope.row[column.prop])">
                      <span
                        v-for="(item, index) in scope.row[column.prop]"
                        :key="index"
                        >{{ item }}</span
                      >
                    </template>
                    <template v-if="!Array.isArray(scope.row[column.prop])">
                      {{ dataFormat(column.prop, scope.row[column.prop]) }}
                    </template>
                  </template>
                </template>
                <template v-else>
                  <expand-dom
                    :column="column"
                    :row="scope.row"
                    :render="column.render"
                    :index="index"
                  >
                  </expand-dom>
                </template>
              </template>
            </template>
          </el-table-column>
        </template>
    </template>
    <!--end-->
    <!--按钮操作组-->
    <el-table-column
      ref="fixedColumn"
      :fixed="operates.fixed"
      label="操作"
      align="center"
      :width="operates.width"
      v-if="
        operates.list.filter((_x) => _x.status === '1' && _x.location === '1')
          .length > 0
      "
    >
      <template slot-scope="scope">
        <el-dropdown
          v-if="
            operates.list.filter(
              (_x) => _x.status === '1' && _x.location === '1'
            ).length > 3
          "
        >
          <span class="el-dropdown-link">
            操作选择<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <div v-for="(btn, index) in operates.list" :key="index">
              <el-dropdown-item
                class="item"
                v-if="btn.status === '1' && btn.location === '1'"
              >
                <el-button
                  size="mini"
                  type="text"
                  :icon="btn.icon"
                  :plain="false"
                  @click="clickEvent(btn, scope.row)"
                  v-hasPermi="['pms:type:edit']"
                  v-if="
                    !($route.path.indexOf('/outer') > -1 && btn.name == '删除')
                  "
                  >{{ btn.name }}
                </el-button>
              </el-dropdown-item>
            </div>
          </el-dropdown-menu>
        </el-dropdown>
        <div class="operate-group" v-else>
          <div v-for="(btn, index) in operates.list" :key="index">
            <template
              class="item"
              v-if="btn.status === '1' && btn.location === '1'"
            >
              <span
                style="cursor: pointer; color: #409eff"
                size="mini"
                :class="btn.icon"
                :plain="false"
                @click="clickEvent(btn, scope.row)"
                v-if="
                  !($route.path.indexOf('/outer') > -1 && btn.name == '删除')
                "
                >{{ btn.name }}
              </span>
            </template>
          </div>
        </div>
      </template>
    </el-table-column>
    <!--end-->
  </el-table>
</template>
<!--end-->
<script>
import {
  getDataList,
  getAddForm,
  delData,
  permissions,
  permissionsNoState,
  previewRecord,
} from "@/api/dynamic/dynamic";
import dynamicFormItem from "@/views/components/dynamicFormItem";
import resize from "@/views/dashboard/mixins/resize";
import Base64 from "@/api/base64";

export default {
  inject: ["app"],
  name: "dynamicTreeTable",
  mixins: [resize],
  props: {
    // 数据列表
    list: {
      type: Array,
      default: () => [],
    },
    /* 需要展示的列 ===
        prop：列数据对应的属性，
        label：列名，
        align：对齐方式，
        width：列宽
      */
    columns: {
      type: Array,
      default: [],
    },
    /* 操作按钮组 ===
        label: 文本，
        type :类型（primary / success / warning / danger / info / text），
        show：是否显示，
        icon：按钮图标，
        plain：是否朴素按钮，
        disabled：是否禁用，
        method：回调方法
      */
    operates: {},
    // table 表格的控制参数
    options: {
      type: Object,
      default: {
        stripe: false, // 是否为斑马纹 table
        highlightCurrentRow: false, // 是否要高亮当前行
        expandColumn: "name",
      },
    },
    //数据更新判断
    flag: true,
    diff: 0,
    scroll: {
      type: String,
      default: "true",
    },
    uncheck: {
      type: Array,
      default: () => {
        return [];
      },
    },
    expandUrl:''
  },
  //组件
  components: {
    expandDom: {
      functional: true,
      props: {
        row: Object,
        render: Function,
        index: Number,
        column: {
          type: Object,
          default: null,
        },
      },
      render: (h, ctx) => {
        const params = {
          row: ctx.props.row,
          index: ctx.props.index,
        };
        if (ctx.props.column) params.column = ctx.props.column;
        return ctx.props.render(h, params);
      },
    },
    dynamicFormItem,
  },
  // 数据
  data() {
    return {
      //创建根节点
      rootList: {
        id: 0,
        label: "root",
        children: [],
        allChildren: [],
        parents: [],
        isroot: true,
        collapsed: true,
        isIndeterminate: false,
        checked: false,
      },
      //id对应列表 便于查询
      listsById: {},
      listTree: null,
      //辅助显示数据实时更新
      toggle: false,
      //已选列表
      multipleSelection: [],
      editall: false,
      addFormData: {},
      defaultExpand: [],
      maxHeight: 200,
      newList: [],
      hasResize: false,
    };
  },
  created() {
    let defaultExpand = sessionStorage.getItem(
      "expand" + this.$route.query.type + this.$route.params.Id
    );
    if (defaultExpand) this.defaultExpand = eval(defaultExpand);

    if (this.$parent.$el) {
      // this.rend = true
      this.tableresize();
    }
  },
  watch: {
    list(val) {
      // console.log(val,this.flag)
      if (val && this.flag) {
        this.UpdateList(val);
        this.toggle = !this.toggle;
      }
    },
  },
  computed: {
    //可视数据
    visibleLists() {
      if (!this.flag) {
        this.toggle = !this.toggle;
        if (this.newList.length == 0) return [];
        const visibleLists = this.newList.filter((item) =>
          this.IsListVisible(item)
        );
        return visibleLists;
      }
    },
  },
  methods: {
    UpdateList(val) {
      // if (val[1] && val[1].rank) this.SortList(val);
      this.newList = [];
      this.rootList = {
        id: 0,
        label: "root",
        children: [],
        allChildren: [],
        parents: [],
        isroot: true,
        collapsed: true,
        isIndeterminate: false,
        checked: false,
      };
      this.ResetListTree(val);
      this.SortList(val)
      this.listTree = this.MakeListTree(this.rootList, val);
      this.newList = this.SortList2(this.rootList);
      // for (let item of this.rootList.children) {
      //   this.GetList(item).collapsed = false;
      // }
      this.SetFlag();
    },
    SortList(val) {
      // val.sort(function (list1, list2) {
      //   let list1_rank = list1.rank ? list1.rank.trim().split(".") : [0];
      //   let list2_rank = list2.rank ? list2.rank.trim().split(".") : [0];
      //   for (let i = 0; ; i++) {
      //     if (list1_rank[i] == undefined && list2_rank[i] == undefined)
      //       return true;
      //     list1_rank[i] =
      //       list1_rank[i] == undefined ? 0 : Number(list1_rank[i]);
      //     list2_rank[i] =
      //       list2_rank[i] == undefined ? 0 : Number(list2_rank[i]);
      //     if (list1_rank[i] - list2_rank[i] != 0) {
      //       return list1_rank[i] - list2_rank[i];
      //     }
      //   }
      // });
      if(val[0]&&val[0].rank){
        let tempIndex = 0
        let firstList = val.filter((item,index)=>{
          // console.log(item,index)
          if(item.rank=='1'){
            tempIndex = index;
            return item
          }
        })[0]
        if(tempIndex!=0){
          let tempList = val[0]
          firstList.rowIndex = '0'
          tempList.rowIndex = tempIndex.toString()
          val[0] = firstList
          val[tempIndex] = tempList
        }
      }
    },
    SortList2(parentList) {
      var newList = [];
      if (parentList.children && parentList.children.length > 0) {
        for (let li of parentList.children) {
          let item = this.GetList(li);
          newList.push(item);
          let appendList = this.SortList2(item);
          if (appendList.length > 0) {
            newList = newList.concat(appendList);
          }
        }
      }
      return newList;
    },
    ResetListTree(lists) {
      // const listById = {};
      var startLevel;
      for (let i in lists) {
        let current = lists[i];
        current.rowIndex = i;
        // if (lists[1] && lists[1].level) {
        //   if (i == 0) {
        //     startLevel = current.level;
        //     // this.rootList.id = current.parentid || 0;
        //   }
        //   // if (current.level == startLevel) {
        //   //   if (!current.parentid) {
        //   //     current.parentid = 0;
        //   //   }
        //   // }
        //   if (current.level == startLevel + 1) {
        //     if (!current.parentid) {
        //       current.parentid = current.projectid;
        //       this.rootList.id = lists[0].parentid;
        //     }
        //     if (this.defaultExpand.indexOf(this.rootList.id) == -1)
        //       this.defaultExpand.push(this.rootList.id);
        //   }
        // } else {
        current.parentId =
          current.parentId == undefined
            ? 0
            : current.parentId == 0&&current.rank
            ? current.projectid
            : current.parentId;
        if (i == 0) {
          this.rootList.id = current.rank&&this.$route.params.Id==current.projectid?current.projectid:current.parentId;
          // this.rootList.id = current.parentid;
          startLevel = current.level || 0;
        }
        // if (
        //   current.level > startLevel &&
        //   current.parentid == this.rootList.id
        // ) {
        //   current.parentid = current.projectid;
        // }
        // }
        current.checked = false;
        current.isIndeterminate = false;
        current.children = [];
        current.allChildren = [];
        current.parents = [];
        if (this.defaultExpand.indexOf(current.id) > -1)
          current.collapsed = false;
        else
        current.collapsed = true;
        this.listsById[current.id] = current;
      }
      // return listById;
    },
    MakeListTree(list, lists) {
      for (let current of lists) {
        if (current.parentId == list.id) {
          if (list.parents.length) {
            list.parents.forEach((parent) => current.parents.push(parent));
          }
          if (list.isroot !== true) {
            current.parents.push(list.id);
            current.parentId = list.id;
          }
          current = this.MakeListTree(current, lists);
          list.allChildren.push(current.id);
          list.children.push(current.id);
          current.allChildren.forEach((childId) =>
            list.allChildren.push(childId)
          );
        }
      }
      return list;
    },
    IsListVisible(list) {
      if (typeof list === "number" || typeof list === "string") {
        list = this.GetList(list);
      }
      if (list.parents.length > 0) {
        for (let i = 0, len = list.parents.length; i < len; i++) {
          let item = this.GetList(list.parents[i]);
          if (item.collapsed) {
            return false;
          }
        }
      }
      return true;
    },
    GetList(listId) {
      if (typeof this.listsById[listId] !== "undefined") {
        return this.listsById[listId];
      }
      return null;
    },
    HandleExpandAll() {
      this.rootList.collapsed = !this.rootList.collapsed;
      for (let item of this.rootList.allChildren) {
        let list = this.GetList(item);
        list.collapsed = this.rootList.collapsed;
      }
      if (this.rootList.collapsed) this.defaultExpand = [];
      else
        this.defaultExpand = [this.rootList].concat(
          this.list.map((item) => {
            return item.id;
          })
        );
      sessionStorage.setItem(
        "expand" + this.$route.query.type + this.$route.params.Id,
        JSON.stringify(this.defaultExpand)
      );
      this.toggle = !this.toggle;
    },
    HandleExpand(id) {
      let list = this.GetList(id);
      list.collapsed = !list.collapsed;
      if(!list.load&&!list.level){
        list.load = true
        let url = this.getUrl(this.expandUrl,list)
        getDataList(url,{loginUser:sessionStorage.getItem('loginUser')||this.$store.state.user.userid}).then(res=>{
          res = JSON.parse(res)
          if(res.rows.length>0){
            this.UpdateList(this.newList.concat(res.rows))
            list.collapsed = false;
            this.toggle = !this.toggle;
          }
        })
      }
      if (list.collapsed) {
        let index = this.defaultExpand.indexOf(id);
        this.defaultExpand.splice(index, 1);
      } else {
        this.defaultExpand.push(id);
      }
      // console.log(this.defaultExpand)
      sessionStorage.setItem(
        "expand" + this.$route.query.type + this.$route.params.Id,
        JSON.stringify(this.defaultExpand)
      );
      this.rootList.collapsed = this.HandleRootCollapsed();
      this.toggle = !this.toggle;
    },
    //行点击事件
    jumpTo(row, column) {
      let params = {};
      let pageParams = JSON.parse(column.pageParams.replace(/'/g, '"'));
      pageParams.url = column.url;
      params.pageParams = pageParams;
      params.rowParams = pageParams.route.indexOf('projectid')>-1?{name:row.projectName}:row;
      params.type = column.url.replace(/\/{id}|\/{projectid}/g, "");
      if(this.$route.query.type&&this.$route.query.type.indexOf('template')>-1&&params.type=='/pmswbs'){
        params.edit = 'pmswbs/editTemplateWbs'
      }
      if(pageParams.route.indexOf('{')>-1){
        pageParams.route = this.getUrl(pageParams.route,row);
        // console.log(pageParams.route)
      }else{
        pageParams.route = pageParams.route + "/" + row.id
      }
      if (this.$route.path.indexOf("/outer") > -1) {
        let routeData = this.$router.resolve({
          path: "/outer/dynamic/" + pageParams.route ,
          query: params,
        });
        const newwin = window.open(
          routeData.href,
          "newwindow",
          `height=${
            0.5 * this.app.screenHeight > 600
              ? 0.5 * this.app.screenHeight
              : 600
          },
                                    width=${
                                      0.5 * this.app.screenWidth > 960
                                        ? 0.5 * this.app.screenWidth
                                        : 960
                                    },
                                    top=${0.2 * this.app.screenHeight},
                                    left=${0.2 * this.app.screenWidth}`
        );
        newwin.route = routeData.route;
      } else {
        this.$router.push({
          path: "/dynamic/" + pageParams.route,
          query: params,
        });
      }
    },
    // 按钮点击事件
    clickEvent(obj, row) {
      let pageParams = JSON.parse(obj.pageParams.replace(/'/g, '"'));
      if (obj.type === "2") {
        if (obj.url) {
          let params = {};
          pageParams.url = obj.url;
          params.rowParams = row;
          params.pageParams = pageParams;
          params.pageParams.title = obj.description;
          this.$router.push({
            path: "/dynamic/" + pageParams.route + "/" + row.id,
            query: params,
          });
        }
      } else {
        if (pageParams.handle == "handleUpdate") {
          this.handleUpdate(obj.url, pageParams.addForm, row);
        } else if (pageParams.handle == "handleTable") {
          this.handleTable(obj.url, pageParams, row.id, obj.description);
        } else if (pageParams.handle == "handleDelete") {
          this.handleDelete(obj.url, obj.description, row);
        } else if (pageParams.handle == "handleConfirm") {
          this.handleConfirm(obj.url, pageParams.method, obj.description, row);
        }
      }
    },
    //修改
    handleUpdate(url, str, row) {
      if (
        row.parentid == 0 &&
        this.dataFormat("typeid", row.typeid).indexOf("项目") > -1
      ) {
        url = this.$route.query.type;
        str = "add_" + this.$route.query.type.trim("/");
      }
      let info = { url, str, id: row.id };
      this.$emit("editChanged", info);
    },
    /** 删除按钮操作 */
    handleDelete(url, title, row) {
      const id = row.name || row.title || row.fileName || row.folderName;
      this.$confirm(`是否确认${title} "${id}"?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delData(url, row.id);
        })
        .then(() => {
          // var obj={pageNum: 1, pageSize: 10};
          this.refreshCurrent();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    handleConfirm(url, method, title, row) {
      this.$confirm(
        `确定${title} "${
          row.name || row.title || row.fileName || row.folderName
        }"?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          baseRequest("/pms" + this.getUrl(url, row), method, {}, {}).then(
            (response) => {
              if (response.code == 200) {
                this.msgSuccess(response.msg);
                this.refreshCurrent();
                return true;
              } else {
                this.msgError(response.msg);
                return true;
              }
            }
          );
        })
        .catch(() => {
          this.msgInfo("已取消");
        });
    },
    //preview预览
    preview(previewUrl, stateId, docId, fileId) {
      if (stateId === undefined) {
        permissionsNoState("views", docId).then((response) => {
          if (response !== 1) {
            this.msgError("您没有此状态下数据的【预览】权限！");
          } else {
            this.previewActions(previewUrl);
            if (docId && fileId) {
              previewRecord(docId, fileId);
            }
          }
        });
      } else {
        permissions("views", stateId).then((response) => {
          if (response !== 1) {
            this.msgError("您没有此状态下数据的【预览】权限！");
          } else {
            this.previewActions(previewUrl);
            if (docId && fileId) {
              previewRecord(docId, fileId);
            }
          }
        });
      }
    },
    previewActions(previewUrl) {
      if (previewUrl == null || previewUrl === "") {
        this.msgError("预览预览地址错误！");
      }
      var close = false;
      const Loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        if (!close) {
          Loading.close();
          this.msgError("预览加载超时,请稍后重试或联系管理员。");
        }
      }, 10000);
      const screenWidth = parseInt(0.5 * document.body.clientWidth); // 预览窗口宽度
      const screenHeight = parseInt(
        0.6 * document.documentElement.clientHeight
      ); // 预览窗口高度
      var strLength = previewUrl.length;
      var str = previewUrl.slice(previewUrl.indexOf(".") + 1, strLength);

      /** 30 预览
      let previewParam = {};
      var url = previewParameter.preview_path;
      previewParam.url = previewParameter.server_url_port;
      previewParam.accesskey = previewParameter.access_key;
      previewParam.secretkey = previewParameter.secret_key;
      previewParam.bucket = str;
      var index = previewUrl.lastIndexOf("/");
      var bucket = previewUrl.substring(0, index);
      var file = previewUrl.substring(index + 1, previewUrl.length);
      previewParam.bucket = bucket;
      previewParam.file = file;
      //水印
      var watermark = this.$store.state.user.name;

      let xhr = new XMLHttpRequest();
      xhr.open("POST", url, true); //建立间接，要求异步响应
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //设置为表单方式提交
      xhr.onreadystatechange =  ()=>{
        //绑定响应状态事件监听函数
        if (xhr.readyState == 4) {
          //监听readyState状态
          if (xhr.status == 200 || xhr.status == 0) {
            //监听HTTP状态码
            if(xhr.responseText==="" || xhr.responseText==null){
              Loading.close();
              close = true
              var rdata = JSON.parse(xhr.responseText);
              if (rdata.success) {
                window.open(
                  rdata.viewurl,
                  "previewwindow",
                  `height=${screenHeight},
                            width=${screenWidth},
                            top=${0.4 * screenHeight},
                            left=${0.5 * screenWidth}`
                );
              }else{
                this.msgError(rdata.msg);
              }
            }else{
              Loading.close();
              close = true
              this.msgError("预览文件错误");
            }
          }
        }
      };
      let data = Base64.encode(previewParam);
      xhr.send("file=" + encodeURIComponent(data)+"&watermark="+watermark+"&cache=false"); //发送请求
      /** 30 预览*/

      /** 120 预览*/
      let strArray = ["img", "png", "html"];
      var url = "";
      if (previewUrl.indexOf("http://") < 0) {
        url = "http://120.77.233.143:81" + previewUrl;
      } else {
        url = previewUrl;
      }
      if (strArray.indexOf(str) > -1) {
        Loading.close();
        close = true;
        if (0) url = "http://localhost:81" + previewUrl;
        window.open(
          url,
          "previewwindow",
          `height=${screenHeight},
                    width=${screenWidth},
                    top=${0.4 * screenHeight},
                    left=${0.5 * screenWidth}`
        );
      } else {
        Loading.close();
        close = true;
        window.open(
          this.settings.previewUrl + "/onlinePreview?url=" +
            encodeURIComponent(Base64.encode(url)),
          "previewwindow",
          `height=${screenHeight},
                    width=${screenWidth},
                    top=${0.4 * screenHeight},
                    left=${0.5 * screenWidth}`
        );
      }
      /** 120 预览*/
    },
    handleTable(url, str, id, title) {
      let info = { url, str, id, title };
      this.$emit("openTable", info);
    },
    HandleRootCollapsed() {
      if (this.rootList.children.length === 0) {
        return false;
      }
      let collapsed = 0;
      for (let item of this.rootList.children) {
        if (this.GetList(item).collapsed) {
          collapsed++;
        }
      }
      return collapsed === this.rootList.children.length;
    },
    TableRowClassName(item) {
      let className = "";
      if (
        item.row.percent < 100 &&
        new Date().valueOf() - new Date(item.row.esfinishdate).valueOf() > 0
      ) {
        className += " expired";
      }
      if (this.options.stripe && item.rowIndex % 2 == 1) {
        className += " striped";
      }
      if (item.row.paste != undefined) {
        className += " paste";
      }
      if (item.row.cut != undefined) {
        className += " cut";
      }
      return className;
    },
    HandleRootCheckedChange(row) {
      let checked = row.checked;
      if (row.allChildren.length > 0) {
        for (let item of row.allChildren) {
          let list = this.GetList(item);
          list.checked = checked;
          list.isIndeterminate = false;
        }
      }
      row.isIndeterminate = false;
      this.toggle = !this.toggle;
      this.UpdateCheckBox(row);
      this.multipleSelection = this.newList.filter((item) => item.checked);
      this.$emit("handleSelectionChange", this.multipleSelection);
    },
    HandleCheckedChange(row) {
      row.isIndeterminate = false;
      this.toggle = !this.toggle;
      this.UpdateCheckBox(row);
      this.multipleSelection = this.newList.filter((item) => item.checked);
      this.$emit("handleSelectionChange", this.multipleSelection);
    },
    UpdateCheckBox(row) {
      if (this.multipleSelection.length == 0) {
        //根选择框
        this.rootList.checked = false;
        this.rootList.isIndeterminate = false;
        //父选择框
        if (row.parents.length > 0) {
          for (let item of row.parents) {
            let list = this.GetList(item);
            list.checked = false;
            list.isIndeterminate = false;
          }
        }
      }
      if(false && row.allChildren.length > 0){
        for (let item of row.allChildren) {
          let childItem = this.GetList(item);
          childItem.checked = row.checked;
        }
      }
      if (
        this.multipleSelection.length > 0 &&
        this.multipleSelection.length < this.list.length
      ) {
        this.rootList.checked = false;
        this.rootList.isIndeterminate = true;
        if (row.parents.length > 0) {
          for (let item of row.parents) {
            let parentList = this.GetList(item);
            if (row.checked) {
              parentList.isIndeterminate = parentList.checked ? false : true;
            }
          }
        }
        if (!row.checked && row.allChildren.length > 0) {
          row.isIndeterminate = false;
          for (let item of row.allChildren) {
            let childItem = this.GetList(item);
            if (childItem.checked) {
              row.isIndeterminate = true;
              break;
            }
          }
        }
      }
      if (this.multipleSelection.length == this.list.length) {
        //根选择框
        this.rootList.checked = true;
        this.rootList.isIndeterminate = false;
        //父选择框
        if (row.parents.length > 0) {
          for (let item of row.parents) {
            let list = this.GetList(item);
            list.checked = true;
            list.isIndeterminate = false;
          }
        }
      }
    },
    SetFlag() {
      this.$emit("SetFlag");
    },
    rightClick(row, column, event) {
      event.preventDefault();
      this.$emit("ContextMenu", event);
    },
    tableresize() {
      if (this.$refs.mutipleTable) {
        // let el = this.$refs.mutipleTable.$el
        let newDiff = this.diff + (this.$route.path.indexOf('outer')>-1?50:0)
        if (this.scroll == "false") {
          this.maxHeight =
            this.app.screenHeight - newDiff > 200
              ? this.app.screenHeight - newDiff
              : 200;
        } else if (this.scroll == "fix") {
          this.maxHeight = 200;
        } else {
          this.maxHeight =
            this.$parent.$el.offsetHeight - newDiff > 200
              ? this.$parent.$el.offsetHeight - newDiff
              : 200;
        }
        // if (
        //   this.scroll ||
        //   this.$refs.mutipleTable.$refs.bodyWrapper.scrollHeight >
        //     this.maxHeight
        // ) {
        //   this.maxHeight =
        //     this.$parent.$el.offsetHeight - this.diff > 200
        //       ? this.$parent.$el.offsetHeight - this.diff
        //       : 200;
        // }
        this.$refs.mutipleTable.$refs.bodyWrapper.scrollTo(0, 0);
      }
      this.widthUpdate(this.columns);
    },
    widthUpdate(val) {
      if (val && this.$parent.$el) {
        var parentWidth = this.$parent.$el.offsetWidth;
        var sum = 0;
        for (let column of val) {
          if (column.width) {
            if (column.show) sum += Number(column.width);
          } else {
            sum = 0;
            break;
          }
        }
        // if (this.options.mutiSelect) parentWidth -= 48;
        if (
          this.operates.list.filter(
            (_x) => _x.status === "1" && _x.location === "1"
          ).length > 0
        ) {
          parentWidth -= 150;
        }
        if (sum && sum < parentWidth) {
          this.hasResize = true;
          for (let column of val) {
            column.showWidth = (column.width / sum) * parentWidth;
          }
        } else {
          this.hasResize = false;
        }
      }
    },
  },
};
</script>

<style lang="scss">
.expand-icon {
  width: 14px;
  height: 14px;
  display: inline-block;
  vertical-align: middle;
  background-size: contain !important;
  cursor: pointer;
  background: url("../../assets/image/add.png") no-repeat;
}
.expand {
  background: url("../../assets/image/minus.png") no-repeat;
}
.operate-group {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
.el-table th.is-leaf,
.el-table td {
  border-bottom: 0;
}
.link-type {
  text-decoration: underline;
  cursor: pointer;
}
.item {
  padding: 0 3px;
}
.el-table .striped {
  background: #eee !important;
}
.el-table .expired {
  color: #f56c6c !important;
}
.el-table .cut {
  color: #f56c6c !important;
  text-decoration: line-through !important;
}
.el-table .paste {
  color: #128303 !important;
}
.remarkpaste {
  color: #128303 !important;
}
.cell {
  width: 100% !important;
}
</style>
